"use client";
import React, { useState, useEffect, useMemo, useRef } from "react";
import Globe from "react-globe.gl";
import { geoDistance, geoInterpolate } from "d3-geo";
import { useGlobeData } from "@/app/cg06/hooks/useGlobeData";
import earthImg from "./earthMap.png";
// import earthImg from "../web/supplyChainNetwork/components/GlobeChart/earth@2x.png";
import starImg from "../../web/supplyChainNetwork/components/GlobeChart/starfield.jpg";
import dotIconAir from "./dotIconAir.svg";
import dotIconGolde from "./dotIconGolde.svg";
import dotIconSea from "./dotIconSea.svg";
import warehouseIcon from "./warehouseIcon.svg";
import warehouseData from "./warehouseData.json";
import { extractUniqueArrays, DiffArys } from "./tools";
import { px2vw, px2vh, responsive } from '@/app/cg06/utils/responsive'; 
import {
  cubicBezier3D,
  polar2Cartesian,
  cartesian2Polar,
  isPointInPolygon,
} from "@/utils/bezier";
import { getScale } from "@/app/cg06/utils/scaleApp";
import "./page.scss";

const MAP_CENTER = [120.08158, 29.31115];

const cartesianList = (lng: number, lat: number, alt: number) => {
  const { x, y, z } = polar2Cartesian(lat, lng, alt);
  return [x, y, z];
};

/**
 *  是否在欧洲
 */
const isInEurope = (latitude: number, longitude: number) => {
  // 欧洲的经纬度范围
  const minLatitude = 35;
  const maxLatitude = 70;
  const minLongitude = -10;
  const maxLongitude = 40;

  // 判断经纬度是否在范围内
  if (
    latitude >= minLatitude &&
    latitude <= maxLatitude &&
    longitude >= minLongitude &&
    longitude <= maxLongitude
  ) {
    return true;
  } else {
    return false;
  }
};

// 简化的美国边界经纬度坐标
const usaBoundary = [
  [-124.848974, 24.396308], // 西南角
  [-66.93457, 24.396308], // 东南角
  [-66.93457, 49.384358], // 东北角
  [-124.848974, 49.384358], // 西北角
];

// 判断经纬度是否在美国范围内
const isInUSA = (lat: number, lon: number) => {
  return isPointInPolygon([lon, lat], usaBoundary);
};

// 是否隐藏仓库
const hiddenWarehouse =
  (typeof window !== "undefined" &&
    new URL(window.location.href).searchParams.get("hiddenWarehouse")) ||
  "";

export default function Earth() {
  const scale = getScale(2240, 1280);
  
  // 根据缩放比例调整固定像素值
  // 这样在缩放后，实际的像素值会保持与设计稿一致
  // 获取 earthBox 的宽度
  const earthBox = document.getElementById("earthBox");

  const height = earthBox?.clientHeight - 82;
  const width = earthBox?.clientWidth;
  const { data } = useGlobeData();
  const [labelData, setLabelData] = useState<any[]>([]);
  const [ringsData, setRingsData] = useState<any[]>([]);
  const globeEl = useRef<any>();

  const routes = useMemo(() => {
    if (!data?.earthObj) return [];
    // 空运和海运的起点 现在都是义乌
    const start = [data?.earthObj.longitude, data?.earthObj.latitude];
    // 空运数据 data?.earthObj.countryObjList 将空运数据（隐藏）
    const airData: any[] = [];
    // 海运数据
    const seaData = data?.earthObj.coordinatesVoList;
    // 两仓一线数据
    const wareData = data?.coordinate || [];
    // 空运
    const airRoutes = airData
      .filter((i) => !!i.latitude && !!i.longitude)
      .map((i) => ({
        startLat: start[1],
        startLng: start[0],
        endLat: i.latitude,
        endLng: i.longitude,
      }));

    // let standardWare: any = []

    const wareRoutes = wareData.map((i) => {
      // if (f.podName === '芝加哥') {
      //   standardWare = f.coordinateData
      //   // return false
      // }
      // standardWare = [...standardWare, ...i.coordinateData]
      return i.coordinateData.map((j) => [
        Number(j.latitude),
        Number(j.longitude),
        1,
        2,
      ]);
    });
    // let diffs: any = []
    // 海运
    const seawayRoutes = seaData.map((i) => {
      const _d = i.coordinatesNodes.map((j) => [
        Number(j.latitude),
        Number(j.longitude),
        1,
        i.lineType,
      ]);
      return _d;
      // const _c = extractUniqueArrays(standardWare, i.coordinatesNodes, i.lineType)
      // diffs.push(..._c)
    });
    // const seawayRoutes = diffs
    // 飞机图标
    const airIconList = airData
      .filter((i) => !!i.latitude && !!i.longitude)
      .map((i) => {
        const start = cartesianList(MAP_CENTER[0], MAP_CENTER[1], 0);
        const end = cartesianList(Number(i.longitude), Number(i.latitude), 0);
        const interpolate = geoInterpolate(
          [MAP_CENTER[0], MAP_CENTER[1], 0],
          [Number(i.longitude), Number(i.latitude), 0]
        );
        const x1 = cartesianList(
          interpolate(0.25)[0],
          interpolate(0.25)[1],
          geoDistance(MAP_CENTER, [i.longitude, i.latitude]) * 0.38
        );
        const x2 = cartesianList(
          interpolate(0.75)[0],
          interpolate(0.75)[1],
          geoDistance(MAP_CENTER, [i.longitude, i.latitude]) * 0.38
        );

        // 三次贝塞尔曲线的中心点
        const centerPoint = cubicBezier3D(0.5, start, x1, x2, end);
        // 中心点的极坐标
        const centerPointPolar = cartesian2Polar({
          x: centerPoint[0],
          y: centerPoint[1],
          z: centerPoint[2],
        });

        return {
          lat: centerPointPolar.lat,
          lng: centerPointPolar.lng,
          elevation: centerPointPolar.altitude,
          name: "airIcon",
        };
      });

    // 海运标签
    const shipLabelLast = seaData.map((i) => ({
      lat: i.coordinatesNodes[i.coordinatesNodes.length - 1].latitude,
      lng: i.coordinatesNodes[i.coordinatesNodes.length - 1].longitude,
      name: i.podCn,
      color:
        i.lineType === 2 ? "rgba(226, 143, 37, 1)" : "rgba(47, 149, 215, 1)",
      backgroundColor:
        i.lineType === 2
          ? "linear-gradient( 180deg, rgba(88,130,173,0.98) 0%, #EEB442 100%)"
          : "linear-gradient( 180deg, rgba(88,130,173,0.98) 0%, #40AAF3 100%)",
      value: i.quantity,
      size: 30,
      icon: i.lineType === 2 ? dotIconGolde.src : dotIconSea.src,
    }));

    // const warehouseLabelList = wareData.map((i) => ({
    //   lat: i.coordinateData[i.coordinateData.length - 1].latitude,
    //   lng: i.coordinateData[i.coordinateData.length - 1].longitude,
    //   name: i.podName,
    //   color: "rgba(226, 143, 37, 1)",
    //   backgroundColor: "linear-gradient( 180deg, rgba(88,130,173,0.98) 0%, #EEB442 100%)",
    //   size: 30,
    //   icon: dotIconGolde.src,
    // }));

    // 空运标签
    const airLabelList = airData.map((i) => ({
      lat: i.latitude,
      lng: i.longitude,
      name: i.name,
      size: 30,
      color: "rgba(0, 249, 177, 1)",
      backgroundColor:
        "linear-gradient( 180deg, rgba(88,130,173,0.98) 0%, #00E9B2 100%)",
      value: i.quantity,
      icon: dotIconAir.src,
    }));

    //船图标
    const shipIconData = seaData.map((i) => {
      const index = Math.floor(i.coordinatesNodes.length * 0.5);

      return {
        lat: i.coordinatesNodes[index].latitude,
        lng: i.coordinatesNodes[index].longitude,
        name: i.lineType === 2 ? "glodShip" : "shipIcon",
      };
    });

    //欧洲标签
    const europeList = [...shipLabelLast, ...airLabelList].filter((i) =>
      isInEurope(Number(i.lat), Number(i.lng))
    );

    //美国标签
    const USAList = [...shipLabelLast, ...airLabelList].filter((i) =>
      isInUSA(Number(i.lat), Number(i.lng))
    );

    //欧洲、美国标签太密集，分两批展示
    const europeList1 = europeList.slice(0, Math.floor(europeList.length / 2));
    const europeList2 = europeList.slice(Math.floor(europeList.length / 2));
    const usaList1 = USAList.slice(0, Math.floor(USAList.length / 2));
    const usaList2 = USAList.slice(Math.floor(USAList.length / 2));
    const htmlLabelList = [...shipLabelLast, ...airLabelList].map((i) => ({
      ...i,
      class: [...europeList1, ...usaList1].some(
        (j) => j.lat === i.lat && j.lng === i.lng
      )
        ? "europe1"
        : [...europeList2, ...usaList2].some(
            (j) => j.lat === i.lat && j.lng === i.lng
          )
        ? "europe2"
        : "",
    }));

    const warehouseList = warehouseData.map((i) => ({
      ...i,
      name: "warehouse",
      lat: i.latitude,
      lng: i.longitude,
    }));

    setLabelData(
      !hiddenWarehouse
        ? [
            ...htmlLabelList.filter((i) => i.value !== "0" && !!i.value ),
            ...shipIconData,
            ...airIconList,
            ...warehouseList,
            { lat: 29.31115, lng: 120.08158, name: "义乌", size: 17 },
          ]
        : [
            ...htmlLabelList,
            ...shipIconData,
            ...airIconList,
            { lat: 29.31115, lng: 120.08158, name: "义乌", size: 17 },
          ]
    );

    setRingsData([
      {
        lat: 29.31115,
        lng: 120.08158,
        maxR: 2,
        propagationSpeed: 1,
        repeatPeriod: 1000,
      },
    ]);
    return [[...seawayRoutes, ...wareRoutes], airRoutes];
  }, [data?.earthObj]);

  useEffect(() => {
    // Auto-rotate
    // globeEl.current.camera.position = [0, 0, 2];
    globeEl.current?.pointOfView(
      { lat: MAP_CENTER[1], lng: MAP_CENTER[0], altitude: 1.8 },
      1000
    );
    globeEl.current.scene().position.y = -10;
    globeEl.current.controls().autoRotate = true;
    globeEl.current.controls().autoRotateSpeed = 1.6;
    globeEl.current.lights()[1].intensity = 0;
  }, []);

  return (
    <>
      {/* <div style={{ width: "100vw", height: "200px" }}>
          <div>义乌</div>
        </div> */}
      <Globe
        width={width}
        animateIn={false}
        height={height}
        ref={globeEl}
        rendererConfig={{
          preserveDrawingBuffer: true,
          powerPreference: "high-performance",
          debug: false,
        }}
        globeImageUrl={earthImg.src}
        backgroundColor="#031E82"
        pathsData={routes[0]}
        pathDashInitialGap={0.01}
        pathDashGap={0.01}
        pathColor={(d: any) => {
          return d[0][3] === 2
            ? "rgba(226, 143, 37, 1)"
            : "rgba(47, 149, 215, 1)";
        }}
        pathStroke={2}
        pathResolution={1}
        pathDashLength={(d) => {
          // return d[0][3] === 2 ? 0.3 : 0.01;
          return 0.01;
        }}
        showAtmosphere
        atmosphereColor="#FFFFFF"
        atmosphereAltitude={0.15}
        pathDashAnimateTime={60000}
        // arcsData={routes[1]}
        arcColor={["rgba(0, 183, 184, 1)", "rgba(0, 249, 177, 1)"]}
        arcDashLength={0.5}
        arcDashGap={0.01}
        arcStroke={0.5}
        arcDashAnimateTime={10000}
        htmlElementsData={labelData}
        ringsData={ringsData}
        ringColor={() => "#fff"}
        ringMaxRadius="maxR"
        ringPropagationSpeed="propagationSpeed"
        ringRepeatPeriod="repeatPeriod"
        ringAltitude={0.005}
        htmlElement={(d: any) => {
          const el = document.createElement("div");
          if (d.name === "义乌") {
            el.innerHTML = `<div class="label-wrap">义乌</div>`;
            return el;
          }
          if (d.name === "shipIcon") {
            el.innerHTML = `<img src="https://uat-base.oss-cn-hangzhou.aliyuncs.com/shiplogo.svg" alt="ship-icon" class="icon">`;
            return el;
          }
          if (d.name === "airIcon") {
            el.innerHTML = `<img src="https://uat-base.oss-cn-hangzhou.aliyuncs.com/airLogo.svg" alt="ship-icon" class="icon">`;
            return el;
          }
          if (d.name === "glodShip") {
            el.innerHTML = `<img src="https://uat-base.oss-cn-hangzhou.aliyuncs.com/glodShip.svg" alt="ship-icon" class="icon"></img>`;

            return el;
          }

          if (d.name === "warehouse") {
            el.innerHTML = `<div class="text-box">
              <div><div class="text-content-w" style="display: flex; align-items: center;">
              <span class="name-txt" style="color: #fff; font-size: 16px">${d.warehouseName} </span>
              </div>
              <span class="tip-line" style="background:linear-gradient( 180deg, rgba(238,180,66,0.98) 0%, #EEB442 100%)"></span></div> <img src="${warehouseIcon.src}" alt="ship-icon" class="warehouse-icon"></img> </div>
            `;

            return el;
          }

          el.innerHTML = `<div class="text-box">
              <div class="${
                d.class
              }"><div class="text-content"> <span class="name-txt" > ${
            d.name
          } </span> <span class="value-txt" style=" color: ${d.color}" > ${
            d.value || 0
          } </span></div>
              <span class="tip-line" style="background:${
                d.backgroundColor
              }"></span></div> <img src="${
            d.icon
          }" alt="ship-icon" class="dot-icon"></img> </div>
            `;
          return el;
        }}
        htmlAltitude={(d: any) => {
          return d.elevation || 0;
        }}
      />
    </>
  );
}
